<template>
  <div>
    <el-form ref="form" :model="articleForm" :rules="rules" style="margin-top: 15px;" size="small" label-width="100px">
      <el-form-item label="文章标题" prop="subject">
        <el-input v-model="articleForm.articleName" style="width: 646px" placeholder="请输入文章标题，文章不能为空" />
      </el-form-item>
      <el-form-item label="栏目" prop="dept.id">
        <treeselect
          v-model="articleForm.dept.id"
          :options="depts"
          :load-options="loadDepts"
          style="width: 178px"
          placeholder="选择栏目"
          @select="deptSelect"
        />
      </el-form-item>
      <el-form-item label="文章概要" prop="summary">
        <div ref="summary" class="summary" />
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-radio v-for="item in dict.article_status" :key="item.id" v-model="articleForm.enabled" :label="item.value">
          {{ item.label }}
        </el-radio>
      </el-form-item>
      <el-form-item label="是否置顶" prop="isTop">
        <el-switch
          v-model="articleForm.isTop"
          active-color="#409EFF"
          inactive-color="#F56C6C"
        />
      </el-form-item>
      <el-form-item label="推送全体用户" prop="push">
        <el-switch
          v-model="articleForm.push"
          active-color="#409EFF"
          inactive-color="#F56C6C"
        />
      </el-form-item>

      <el-form-item label="价格" prop="price">
        <el-input v-model="articleForm.price" style="width: 100px" />
        <span>元</span>
        <el-checkbox v-model="articleForm.vipFree" style="margin-left: 15px;">VIP是否免费</el-checkbox>
      </el-form-item>
      <el-button
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-upload"
        @click="crud.toAdd"
      >
        添加附件
      </el-button>
      <div v-if="fileLists && fileLists.length > 0" style="height:70px;margin-top: 20px;display: flex;flex-direction: row; align-items: flex-start;flex-wrap: wrap;">
        <template v-for="file in fileLists">
          <div :key="file.id" style="margin-left: 20px;display: flex; flex-direction: column; align-items: center;">
            <el-image
              v-if="file.type==='图片'"
              style="width: 100px;height: 50px;"
              :src="baseApi + '/file/' + file.type + '/' + file.realName"
              :preview-src-list="[baseApi + '/file/' + file.type + '/' + file.realName]"
            />
            <video v-if="file.type==='视频'" controls :src="baseApi + '/file/' + file.type + '/' + file.realName" style="width: 100px;height: 50px;" />
            <audio v-if="file.type==='音乐'" controls :src="baseApi + '/file/' + file.type + '/' + file.realName" style="width: 250px;height: 50px;" />
            <svg-icon v-if="file.type === '文档' && file.realName.indexOf('.pdf') > 0" style="width: 100px;height: 50px;" icon-class="pdf" />
            <svg-icon v-if="file.type === '文档' && file.realName.indexOf('.pdf') < 0" style="width: 100px;height: 50px;" icon-class="attachmentdoc" />
            <span style="max-width: 10em;margin-top:15px;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color: #1890ff;font-size: 13px;"><a
              class="el-link--primary"
              style="color: #1890ff;"
              target="_blank"
              @click="deleteFile(file)"
            >
              <i class="el-icon-delete" style="width: 20px;height: 20px;" />
            </a>{{ file.name }}</span>
          </div>
        </template>
      </div>
      <div ref="editor" class="editor" />
      <el-button
        :loading="loading"
        style="margin-left:1.6%;margin-bottom: 30px"
        size="medium"
        type="primary"
        @click="doSubmit"
      >保存文章
      </el-button>
    </el-form>
    <!--表单组件-->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.add ? '文件上传' : '编辑文件'" width="500px">
      <el-form ref="form" :model="form" size="small" label-width="80px">
        <el-form-item label="文件名">
          <el-input v-model="form.name" style="width: 370px;" />
        </el-form-item>
        <!--   上传文件   -->
        <el-form-item v-if="crud.status.add" label="上传">
          <el-upload
            ref="upload"
            :limit="1"
            :before-upload="beforeUpload"
            accept="audio/*, image/*,video/*,.doc,.pdf,.docx"
            :auto-upload="false"
            :headers="headers"
            :on-success="handleSuccess"
            :on-error="handleError"
            :on-change="handleChange"
            :action="fileUploadApi + '?name=' + form.name"
          >
            <div class="eladmin-upload"><i class="el-icon-upload" /> 添加文件</div>
            <div slot="tip" class="el-upload__tip">可上传图片,视频,音频,pdf,word文档，且不超过500M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="loading" type="primary" @click="upload">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, edit, getArticle } from '@/api/system/article'
import { getDepts, getDeptSuperior } from '@/api/system/dept'
import { upload } from '@/utils/upload'
import { getToken } from '@/utils/auth'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudFile from '@/api/tools/localStorage'
import { mapGetters } from 'vuex'
import E from 'wangeditor'
import Treeselect, { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
const defaultForm = { id: null, name: '' }
export default {
  name: 'ArticleDetail',
  components: { Treeselect },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '文件', queryOnPresenterCreated: false, url: 'api/localStorage', crudMethod: { ...crudFile }})
  },
  data() {
    return {
      loading: false,
      articleForm: { articleName: '', summary: '', content: '', isTop: false, push: false, enabled: 'true', dept: {}, price: 0, attachmentIds: [], vipFree: false },
      rules: {
        articleName: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        summary: [
          { required: true, message: '概要不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ]
      },
      deptName: '', depts: [], deptDatas: [],
      headers: { 'Authorization': getToken() },
      fileLists: []
    }
  },
  // 设置数据字典
  dicts: ['article_status', 'top_status'],
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi',
      'fileUploadApi'
    ])
  },
  mounted() {
    const _this = this
    this.crud.optShow.add = false

    var e2 = new E(this.$refs.summary)
    // 自定义菜单配置
    e2.config.zIndex = 10
    e2.config.showFullScreen = false
    // 配置菜单栏，删减菜单，调整顺序
    e2.config.menus = [
      'bold',
      'italic',
      'underline',
      'indent',
      'lineHeight',
      'foreColor'
    ]

    e2.config.onchange = (html) => {
      this.articleForm.summary = html
    }
    // 设置编辑区域高度为 500px
    e2.config.height = 200
    e2.create()

    var editor = new E(this.$refs.editor)
    // 自定义菜单配置
    editor.config.zIndex = 10
    // 文件上传
    editor.config.customUploadImg = function(files, insert) {
      // files 是 input 中选中的文件列表
      // insert 是获取图片 url 后，插入到编辑器的方法
      files.forEach(image => {
        upload(_this.imagesUploadApi, image).then(res => {
          const data = res.data
          const url = _this.baseApi + '/file/' + data.type + '/' + data.realName
          insert(url)
        })
      })
    }
    editor.config.excludeMenus = ['video', 'code']
    editor.config.onchange = (html) => {
      this.articleForm.content = html
    }
    editor.config.height = 600
    editor.create()
    this.getDepts(() => {
      if (this.$route.query.id) {
        getArticle(this.$route.query.id).then(res => {
          res.enabled = res.enabled ? 'true' : 'false'
          this.articleForm = res
          this.fileLists = res.attachments || []
          editor.txt.html(this.articleForm.content)
          e2.txt.html(this.articleForm.summary.replaceAll(' ', '&nbsp;').replaceAll('\n', '<br />'))
          const dept = this.depts.find(v => v.id === this.articleForm.dept.id)
          if (!dept) {
            this.getSupDepts([this.articleForm.dept.id])
          }
        })
      } else if (this.$route.query.deptId) {
        this.articleForm.dept.id = this.$route.query.deptId
        const dept = this.depts.find(v => v.id === this.articleForm.dept.id)
        if (!dept) {
          this.getSupDepts([this.articleForm.dept.id])
        }
      }
    })
  },
  methods: {
    handleChange(file, fileList) {
      this.form.name = file.name
    },
    deleteFile(file) {
      this.$confirm(`确认删除${file.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('删除file', file)
        this.crud.doDelete([file])
        this.fileLists.splice(this.fileLists.indexOf(file), 1)
      }).catch(() => {
      })
    },
    upload() {
      this.$refs.upload.submit()
    },
    deptSelect(node, instanceId) {
      console.log('node:', node)
      console.log('instanceId:', instanceId)
      if (!node.leaf) {
        this.$message.error('不能选择顶级栏目, 请选择二级栏目')
      }
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 500
      if (!isLt2M) {
        this.loading = false
        this.form.name = ''
        this.$message.error('上传文件大小不能超过 500MB!')
      }
      console.log(file)
      if (this.fileLists.find(v => v.type === '视频') && file.type.indexOf('video') >= 0) {
        this.loading = false
        this.form.name = ''
        this.$message.error('已经存在一个视频附件!')
        isLt2M = false
      }
      if (this.fileLists.find(v => v.type === '音乐') && file.type.indexOf('audio') >= 0) {
        this.loading = false
        this.form.name = ''
        this.$message.error('已经存在一个音频附件!')
        isLt2M = false
      }
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      console.log(response)
      this.fileLists.push(response)
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      this.crud.status.add = CRUD.STATUS.NORMAL
      this.crud.resetForm()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.fileLists) {
            this.articleForm.attachmentIds = this.fileLists.map(v => `${v.id}`).join(';')
          }
          this.articleForm.content = this.articleForm.content.replaceAll('<b></b>', '').replaceAll('</b><b>', '')
          const execute = this.articleForm.id ? edit : add
          execute(this.articleForm).then(res => {
            this.$notify({
              title: '保存成功',
              type: 'success',
              duration: 2500
            })
            this.loading = false
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.back()
          }).catch(err => {
            this.loading = false
            console.log(err.response.data.message)
          })
        } else {
          return false
        }
      })
    },
    getDepts(callback) {
      getDepts({ enabled: true, pidIsNull: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
        callback && callback()
      })
    },
    getSupDepts(deptId) {
      getDeptSuperior(deptId).then(res => {
        const date = res.content
        this.buildDepts(date)
        this.depts = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    }
  }
}
</script>

<style scoped>
.editor {
  text-align: left;
  margin: 20px;
  width: 730px;
}
.summary {
  text-align: left;
  width: 640px;
  height: 100px;
  display:inline-block;
}
.filter-item {
  margin-left: 20px;
}
/* ::v-deep .w-e-text-container {
  height: 360px !important;
} */

</style>
